import React, { useState, useEffect } from 'react';
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { IDomEditor, IEditorConfig, IToolbarConfig, Boot, IModuleConf } from '@wangeditor/editor';
import type { InsertImgFnType, PropsType, InsertVidoeFnType } from './index.d';
import PrintMenu from './lib/print';
const Wangeditor: React.FC<PropsType> = ({ value, onChange }) => {
  const [editor, setEditor] = useState<IDomEditor | null>(null); // 存储 editor 实例
  // 菜单注册
  const menuConf = {
    key: 'print12',
    factory() {
      return new PrintMenu();
    },
  };
  // Boot.registerMenu(menuConf);
  const module: Partial<IModuleConf> = {
    // TS 语法
    menus: [menuConf],

    // 其他功能，下文讲解...
  };
  Boot.registerModule(module);
  const toolbarConfig: Partial<IToolbarConfig> = {};
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {
        // 小于该值就插入 base64 格式（而不上传），默认为 0
        base64LimitSize: 5 * 1024, // 5kb
        // 单个文件的最大体积限制
        maxFileSize: 2 * 1024 * 1024,
        // 自定义上传
        async customUpload(file: File, insertFn: InsertImgFnType) {
          const formData = new FormData();
          formData.append('file', file);
          // ...上传
        },
      },
      uploadVideo: {
        // 自定义上传
        async customUpload(file: File, insertFn: InsertVidoeFnType) {
          const formData = new FormData();
          formData.append('file', file);
          // ...上传
        },
      },
    },
  };

  // 及时销毁 editor
  useEffect(() => {
    return () => {
      if (editor === null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);
  return (
    <>
      <Toolbar
        editor={editor}
        defaultConfig={toolbarConfig}
        mode="default"
        style={{ borderBottom: '1px solid #ccc' }}
      />
      <Editor
        defaultConfig={editorConfig}
        value={value}
        onCreated={setEditor}
        onChange={(editor) => onChange?.(editor?.isEmpty() ? '' : editor?.getHtml())}
        mode="default"
        style={{ height: '500px' }}
      />
    </>
  );
};

export default Wangeditor;
